<?php
/**
 * 验证码类
 * $Id$
 */

class captcha {
	/**
	 * 图片文件类型
	 */
	private $img_type = 'png';

	/**
	 * 验证码长度
	 */
	private $length = 4;

	/**
	 * 字体大小
	 */
	private $font = 5;

	/**
	 * 存在session中的名称
	 */
	private $session_word = 'captcha_word';

	/**
	 * 图片宽度
	 */
	private $width = 130;

	/**
	 * 图片高度
	 */
	private $height = 20;

	/**
	 * 构造函数
	 */
	public function __construct($width = 145, $height = 20) {
		$this->width = $width;
		$this->height = $height;
		
		/* 检查是否支持GD*/
		return (function_exists('imagecreatetruecolor') || function_exists('imagecreate'));
	}

	/**
	 * 检查验证码是否和 session中的一样
	 */
	public function check_word($word) {
		$recorded = isset($_SESSION[$this->session_word]) ? base64_decode($_SESSION[$this->session_word]) : '';
		$given = $this->encrypts_word($word);

		return preg_match('/'.$given.'/', $recorded);
	}

	/**
	 * 生成图片并且输出到浏览器
	 */
	public function generate_image($word = false) {
		if (!$word) {
			$word = $this->generate_word();
		}

		/* 记录验证码到SESSION*/
		$this->record_word($word);

		/* 验证码长度*/
		$count = strlen($word);

		/* 创建图片*/
		$img = imagecreate($this->width, $this->height);
		/*设置图片被景色*/
		imagecolorallocate($img,255,255,255);
		$pix_color = imagecolorallocate($img, mt_rand(30,180), mt_rand(10,100), mt_rand(40,200));

		/* 每个字符所占用的宽度*/
		$per_width = $this->width / $this->heigth;
		for ($i = 0; $i < $this->length; $i++) {
			$x = mt_rand($i * $per_width, ($i+1) * $per_width - $this->font);
			$y = mt_rand(0, ($this->height - $this->font));
			$text_color = imagecolorallocate($img, mt_rand(30, 180), mt_rand(10, 100), mt_rand(49, 250));
			imagechar($img, $this->font, $x, $y, $word[$i], $text_color);
		}
		/* 给图片添加一些杂乱的点*/
		for($j = 0; $j < 50; $j++){
			$x = mt_rand(0, $this->width);
			$y = mt_rand(0,$this->height);
			imagesetpixel($img,$x,$y,$pixColor);
		}
	}

	/**
	 * 对需要记录的字符串进行加密
	 */
	public function encrypts_word($word) {
		return substr(md5(strtoupper($word)), 1, 10);
	}

	/**
	 * 把验证码保存在 SESSION
	 */
	public function record_word($word) {
		$_SESSION[$this->session_word] = base64_encode($this->encrypts_word($word));
	}

	/**
	 * 生成随机验证码
	 */
	public function generate_word($length = 4) {
		if ($length) {
			$this->length = $length;
		}
		$chars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
		for ($i =0, $count = strlen($chars); $i < $count; $i++) {
			$arr[$i] = $chars[i];
		}

		mt_srand((double)microtime() * 1000000);
		shuffle($arr);

		return substr(implode('', $arr), 5, $length);
	}
}
